﻿using System;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;
using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.FFMPEG;

namespace AutoStar.Views
{
    public partial class WindowMonitor : Window
    {
        private FilterInfoCollection _videoDevices; // 视频设备列表
        private VideoCaptureDevice _videoSource;    // 视频源
        private bool _isRecording = false;          // 是否正在录像
        private string _outputFolder = "Output";    // 输出文件夹

        public WindowMonitor()
        {
            InitializeComponent();
            LoadVideoDevices(); 
            CreateOutputFolder();
        }
        // 创建输出文件夹
        private void CreateOutputFolder()
        {
            if (!Directory.Exists(_outputFolder))
            {
                Directory.CreateDirectory(_outputFolder);
            }
        }
        // 加载视频设备
        private void LoadVideoDevices()
        {
            _videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            VideoDevice.ItemsSource = _videoDevices;
            VideoDevice.DisplayMemberPath = "Name"; // 显示设备名称
            VideoDevice.SelectedIndex = 0;
        }

        // 连接摄像头按钮点击事件
        [Obsolete]
        private void ConnectCamera_Click(object sender, RoutedEventArgs e)
        {
            if (_videoDevices.Count == 0)
            {
                MessageBox.Show("未找到摄像头设备。");
                return;
            }

            try
            {
                // 如果已经连接摄像头，先停止
                if (_videoSource != null && _videoSource.IsRunning)
                {
                    _videoSource.SignalToStop();
                    _videoSource.WaitForStop();
                    _videoSource.NewFrame -= VideoSource_NewFrame; // 移除事件绑定
                    _videoSource = null; // 释放摄像头对象
                }

                // 初始化摄像头
                _videoSource = new VideoCaptureDevice(_videoDevices[VideoDevice.SelectedIndex].MonikerString);

                // 设置帧尺寸（如果需要）
                _videoSource.DesiredFrameSize = new System.Drawing.Size(640, 480); // 或其他分辨率
                _videoSource.DesiredFrameRate = 30; // 设置帧率

                _videoSource.NewFrame += VideoSource_NewFrame; // 绑定新帧事件
                _videoSource.Start(); // 启动摄像头

                // 重置帧尺寸变量
                _frameWidth = 0;
                _frameHeight = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"摄像头连接失败: {ex.Message}");
            }
        }
        //private void ConnectCamera_Click(object sender, RoutedEventArgs e)
        //{
        //    if (_videoDevices.Count == 0)
        //    {
        //        MessageBox.Show("未找到摄像头设备。");
        //        return;
        //    }

        //    try
        //    {
        //        // 如果已经连接摄像头，先停止
        //        if (_videoSource != null && _videoSource.IsRunning)
        //        {
        //            _videoSource.SignalToStop();
        //            _videoSource.WaitForStop();
        //        }

        //        // 初始化摄像头
        //        _videoSource = new VideoCaptureDevice(_videoDevices[VideoDevice.SelectedIndex].MonikerString);
        //        _videoSource.NewFrame += VideoSource_NewFrame; // 绑定新帧事件
        //        _videoSource.Start(); // 启动摄像头
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show($"摄像头连接失败: {ex.Message}");
        //    }
        //}
        // 摄像头新帧事件
        private int _frameWidth = 0;
        private int _frameHeight = 0;

        private void VideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            try
            {
                // 获取当前帧
                var frame = (Bitmap)eventArgs.Frame.Clone();

                // 如果尚未获取帧尺寸，则记录下来
                if (_frameWidth == 0 || _frameHeight == 0)
                {
                    _frameWidth = frame.Width;
                    _frameHeight = frame.Height;
                }

                // 将新帧显示到 VideoSourcePlayer
                Dispatcher.Invoke(() =>
                {
                    videoSourcePlayer.VideoSource = _videoSource;
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"帧处理失败: {ex.Message}");
            }
        }
        //private void VideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
        //{
        //    try
        //    {
        //        // 将新帧显示到 VideoSourcePlayer
        //        Dispatcher.Invoke(() =>
        //        {
        //            videoSourcePlayer.VideoSource = _videoSource;
        //        });
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show($"帧处理失败: {ex.Message}");
        //    }
        //}

        // 拍照按钮点击事件
        private void TakePicture_Click(object sender, RoutedEventArgs e)
        {
            if (_videoSource == null || !_videoSource.IsRunning) return;

            var frame = videoSourcePlayer.GetCurrentVideoFrame();
            if (frame != null)
            {
                var bitmapImage = BitmapToImageSource(frame);
                CapturedImage.Source = bitmapImage;

                // 保存照片
                var fileName = Path.Combine(_outputFolder, $"Photo_{DateTime.Now:yyyyMMdd_HHmmss}.jpg");
                frame.Save(fileName);
            }
        }

        // 将 Bitmap 转换为 BitmapImage
        private BitmapImage BitmapToImageSource(System.Drawing.Bitmap bitmap)
        {
            using (var memory = new MemoryStream())
            {
                bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp);
                memory.Position = 0;
                var bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = memory;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
                return bitmapImage;
            }
        }

        // 开始录像
        private async void StartRecording_Click(object sender, RoutedEventArgs e)
        {
            if (_isRecording) return;

            _isRecording = true;

            // 创建录像文件名
            string videoFileName = Path.Combine(_outputFolder, $"Recording_{DateTime.Now:yyyyMMdd_HHmmss}.avi");

            // 确保帧尺寸已获取
            if (_frameWidth == 0 || _frameHeight == 0)
            {
                MessageBox.Show("无法获取摄像头帧尺寸，请检查摄像头是否正常工作。");
                _isRecording = false;
                return;
            }

            // 使用 AForge.Video.FFMPEG 进行录像
            await Task.Run(() =>
            {
                using (var writer = new VideoFileWriter())
                {
                    // 设置视频文件的编码格式和帧率
                    writer.Open(videoFileName, _frameWidth, _frameHeight, 30, VideoCodec.MPEG4);

                    while (_isRecording)
                    {
                        try
                        {
                            // 获取当前帧
                            var frame = videoSourcePlayer.GetCurrentVideoFrame();
                            if (frame != null)
                            {
                                // 将帧写入视频文件
                                writer.WriteVideoFrame(frame);
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"录像失败: {ex.Message}");
                            break;
                        }
                    }

                    writer.Close();
                }
            });
        }
        // 调整 Bitmap 尺寸的方法
        private System.Drawing.Bitmap ResizeBitmap(System.Drawing.Bitmap bitmap, int width, int height)
        {
            var resizedBitmap = new System.Drawing.Bitmap(width, height);
            using (var g = System.Drawing.Graphics.FromImage(resizedBitmap))
            {
                g.DrawImage(bitmap, 0, 0, width, height);
            }
            return resizedBitmap;
        }

        // 暂停录像
        private void PauseRecording_Click(object sender, RoutedEventArgs e)
        {
            _isRecording = false;
        }

        // 结束录像
        private void StopRecording_Click(object sender, RoutedEventArgs e)
        {
            _isRecording = false;
            // 停止录像并保存文件
        }

        // 打开照片文件夹
        private void OpenPictureFolder_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start(_outputFolder);
        }

        // 打开视频文件夹
        private void OpenVideoFolder_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start(_outputFolder);
        }
        private async Task StopVideoSourceAsync()
        {
            if (_videoSource != null && _videoSource.IsRunning)
            {
                _videoSource.SignalToStop();

                // 异步等待摄像头停止，设置超时时间
                var stopTask = Task.Run(() => _videoSource.WaitForStop());
                await Task.WhenAny(stopTask, Task.Delay(5000)); // 等待 5 秒超时

                if (!stopTask.IsCompleted)
                {
                    Global.LogHelper.WriteLog("摄像头停止超时，强制停止");
                }
            }
        }
        private async void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            await StopVideoSourceAsync();
            _videoSource = null;
        }
        private void StopVideoSource()
        {
            if (_videoSource != null && _videoSource.IsRunning)
            {
                _videoSource.SignalToStop();

                // 在后台线程中调用 WaitForStop
                Task.Run(() =>
                {
                    _videoSource.WaitForStop();
                });
            }
        }
    }
}